﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Hands.UriRewrite.OverwriteException;

namespace Hands.UriRewrite
{
    internal class UriBranchPath : IRewrite
    {
        private readonly string branchPath = null;
        private readonly StringBuilder rewriteTo = null;

        private readonly List<string> paraNames = new List<string>();

        internal UriBranchPath(string branchPath, StringBuilder rewriteTo)
        {
            this.branchPath = branchPath;
            this.rewriteTo = rewriteTo;
        }

        internal void parsingParaName(string configBranchPath)
        {
            foreach (Match para in RegularExpressionsRule.PARSING_CONFIG_URI_PARA_REGEX.Matches(configBranchPath))
            {
                paraNames.Add(para.Value);
            }
        }


        public string rewrite(string uri)
        {
            MatchCollection paraValues = RegularExpressionsRule.PARSING_PARA_VALUE_REGEX.Matches(uri.Replace(branchPath, string.Empty));

            if (paraValues.Count != paraNames.Count)
            {
                throw new ParaAmountIsNotConsistentException();
            }

            int length = paraValues.Count;

            StringBuilder rewriteToUri = null;

            for (int i = 0; i < length; i++)
            {
                rewriteToUri = rewriteTo.Replace(paraNames[i], paraValues[i].Value);
            }
            return rewriteToUri.ToString();
        }
    }
}
